import axios from "axios";
import { getToken } from "./token";
import router from "@/routers";


//配置根域名，超时时间
const request = axios.create({
    baseURL: 'http://geek.itheima.net/v1_0',
    timeout: 5000
})

// 请求拦截
request.interceptors.request.use(config => {
    // 拦截请求
    // 1. 添加token
    if(getToken()) {
        config.headers.Authorization = `Bearer ${getToken()}`
    }
    return config
}, err => {
    return Promise.reject(err)
})

// 响应拦截
request.interceptors.response.use(res => {
    // 拦截响应
    //对于状态码为200范围内的都会触发
    return res.data
}, err => {
    //
    if(err.response.status === 401) {
        // 清除token
        localStorage.clear()
        // 跳转到登录页面
        // window.location.href = '/login'
        router.navigate('/login',{ replace: true })
    }
    return Promise.reject(err)
})

export default request